const { Service } = require('egg')
const ejsExcel = require('ejsexcel');
const moment = require('moment');
const fs = require('fs')



//导出文件
class ExportService extends Service{
     /**
     * 导出文件
     * @param {*} payload  
     * @param {*} file_path
     * @returns 
     */
    async export(dataSource, file_path){
        const { ctx } = this;
        // //调用导出报表函数
        // var dataSource={
        //     reports:result
        // };
        let xlsFile = this.config.appBaseDir + file_path
        var xlsBuf = fs.readFileSync(xlsFile);
        return new Promise((resolve, reject)=>{
            ejsExcel.renderExcelCb(xlsBuf, dataSource, (err,xlsUpdatedBuf)=>{
                if(err) {
                    console.error(err);
                    ctx.body= '<h1>报表导出出错了</h1>';
                    reject();
                }
                else
                {
                    var data = new Buffer(xlsUpdatedBuf,'binary');
                    var fileName=moment().format('YYYYMMDDHHmmssSSSS');
                    ctx.set('Content-Type', 'application/vnd.openxmlformats');
                    ctx.set("Content-Disposition", "attachment; filename=" + fileName+".xlsx");
                    ctx.body= data;
                    resolve();
                }
            });
        });
    }
}

module.exports = ExportService